package com.home.manager.common;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.home.manager.bean.User;
import com.home.manager.utils.Decoded;
import com.home.manager.utils.UserThreadLocal;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoginInterceptor implements HandlerInterceptor {

    private final String ur = "ur";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String userRole = request.getParameter(ur);
        if (!StringUtils.hasText(userRole)) {
            return HandlerInterceptor.super.preHandle(request, response, handler);
        }
        try {
            String userRoles = Decoded.base64(userRole);
            ObjectMapper objectMapper = new ObjectMapper();
            User testBean = objectMapper.readValue(userRoles, User.class);
            UserThreadLocal.addCurrentUser(testBean);
        } catch (Exception e) {
        }

        return HandlerInterceptor.super.preHandle(request, response, handler);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

        UserThreadLocal.remove();
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
